package net.qiqbframework.spring.accessing;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.concurrent.atomic.AtomicReference;

public class AggregateClientApiFactoryBean<T> implements FactoryBean<T>, ApplicationContextAware {

    private final Class<T> interfaceClass;

    private ApplicationContext applicationContext;

    private AtomicReference<T> target = new AtomicReference<>();

    public AggregateClientApiFactoryBean(Class<T> interfaceClass) {
        this.interfaceClass = interfaceClass;

    }

    public void setTarget(T target) {
        if (target == null) {
            throw new IllegalArgumentException("target not null");
        }
        if (this.target.get() != null && this.target.get() != target) {
            throw new IllegalArgumentException("找到多个target 无法确定哪个");
        }
        this.target.set(target);
    }

    public void verifyTarget() {
        if (target.get() == null) {
            throw new IllegalArgumentException("target not null");
        }
    }

    @Override
    public T getObject() throws Exception {

        Object proxy = Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                new Class[]{interfaceClass},
                new BlockClientProxyHandler<>(interfaceClass, target)
        );
        return (T) proxy;
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
